<?php
/**
 * Created by EditPlus.
 * User: GRAY <iamgray@gmail.com>
 * Date: 8/4/16
 * Time: 19:43
 */

namespace Home\Controller;

use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Controller;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Think\Log;
use Common\Vendor\Hook\BaseHook;
include('MaiBei/Common/Library/zima/ZmopSdk.php');
include('MaiBei/Common/Library/zhima/zmop/ZmopClient.php');
include('MaiBei/Common/Library/zhima/zmop/request/ZhimaAuthInfoAuthorizeRequest.php');  
include('MaiBei/Common/Library/zhima/zmop/request/ZhimaCreditScoreGetRequest.php');  

class ZhimaController extends Controller {

    //芝麻信用网关地址
    public $gatewayUrl = "https://zmopenapi.zmxy.com.cn/openapi.do";
    //商户私钥文件
    public $privateKeyFile = __DIR__ ."/../../Common/Library/zhima/zmop/cert/rsa_private_key.pem";
    //芝麻公钥文件
    public $zmPublicKeyFile = __DIR__ ."/../../Common/Library/zhima/zmop/cert/zima_public_key.pem";
    //数据编码格式
    public $charset = "UTF-8";
    //芝麻分配给商户的 appId
    public $appId = "xxxxxx";

    public function __construct() {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }
    //授权成功后芝麻回调
    public function notifyUrl() {
        $params = $_GET['params'];
        $sign =  $_GET['sign'];
        $result = $this->zhimacallback($params,$sign);
        if($result['error_code']=='SUCCESS') {
            $open_id = $result['open_id'];
            $CustomerID = $result['state'];

            $response = $this->ZhimaCreditScoreGet($open_id);
            $zm_score = $response->zm_score;
            $biz_no = $response->biz_no;
            //入库
             M('CustomerAuth')->where(['customer_id'=>$CustomerID])->setField(['open_id'=>$open_id,'zm_score'=>$zm_score,'biz_no'=>$biz_no,'zhima_pass'=>1]);
            //echo "认证完成";
            header("Location: http://api.9maibei.com/wx_h5/app/index.html#/sesame_success");
        } else {
            //echo "FAIL";
            header("Location: http://api.9maibei.com/wx_h5/app/index.html#/sesame_auth");

        }
    }
    //h5调用获取跳转URL
    public function ZhimaAuthInfoAuthorize(){
        try {
            $name = I("post.name", '', 'string');
            $certNo = I("post.id_num", '', 'string');
            //$customerId = I('post.customer_id', 0, 'intval');
            BusinessException::throwException('暂未开放');
            $customerId = M('Customer')->where("id_num='$certNo' AND type in (1,3)")->getField('id');
            if(!$customerId) {
                BusinessException::throwException('身份证号不存在');
            }

            $client = new \ZmopClient($this->gatewayUrl,$this->appId,$this->charset,$this->privateKeyFile,$this->zmPublicKeyFile);
            $request = new \ZhimaAuthInfoAuthorizeRequest();
            $request->setChannel("app");
            $request->setPlatform("zmop");
            $request->setIdentityType("2");// 必要参数         
            $request->setIdentityParam("{\"name\":\"$name\",\"certType\":\"IDENTITY_CARD\",\"certNo\":\"$certNo\"}");// 必要参数         
            $request->setBizParams("{\"auth_code\":\"M_H5\",\"channelType\":\"app\",\"state\":\"$customerId\"}");// 
            $url = $client->generatePageRedirectInvokeUrl($request);
            if($url) {
                $ret = Constant::getReturn(Constant::SUCCESS);
                $ret['data'] =  array('url'=>$url);
            } else {
                BusinessException::throwException('获取URL失败');
            }
        } catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    //获取芝麻分
    public function ZhimaCreditScoreGet($open_id){
        $client = new \ZmopClient($this->gatewayUrl,$this->appId,$this->charset,$this->privateKeyFile,$this->zmPublicKeyFile);
        $request = new \ZhimaCreditScoreGetRequest();
        $request->setChannel("apppc");
        $request->setPlatform("zmop");
        $tid = date('YmdHis').mt_rand(100,999).time().mt_rand(100,999);
        $request->setTransactionId($tid);//必要参数，业务流水号
        $request->setProductCode("w1010100100000000001");//必要参数，这个值对于芝麻分产品是固定的，无需修改
        $request->setOpenId($open_id);//必要参数，授权获得的openid
        //print_r($request);exit;
        $response = $client->execute($request);
        return $response;
        //echo json_encode($response);
        //{"success":true,"biz_no":"ZM201610263000000556600308114916","zm_score":"688"}
    }
    //解密函数
    public  function zhimacallback($params,$sign){
        //$this->privateKeyFile= "./cert/rsa_private_key.pem";
        $client = new \ZmopClient($this->gatewayUrl, $this->appId, $this->charset, $this->privateKeyFile,$this->zmPublicKeyFile);
        $result=$client->decryptAndVerifySign($params,$sign);
        //echo $result;
        //open_id=268803904375259775763039660&error_message=%E6%93%8D%E4%BD%9C%E6%88%90%E5%8A%9F&state=%E5%95%86%E6%88%B7%E8%87%AA%E5%AE%9A%E4%B9%89&error_code=SUCCESS&app_id=1000791&success=true
        parse_str($result,$result1);
        //$open_id = $result1['open_id'];

        return $result1;
        //print_r($result1);
        //return $result;
    }

}
